﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using System.Xml;

namespace DE.Sdc.SharePoint.SPContentStructure.Import
{
    [Serializable]
    [XmlType(AnonymousType = true, Namespace = DeploymentConstants.Namespace)]
    [XmlRoot(Namespace = DeploymentConstants.Namespace, IsNullable = false)]
    public class Views : IImportDefinition<SPList, SPWeb>
    {
        public Views()
        {
            Items = new List<View>();
        }

        [XmlAttribute]
        public bool RemoveExisting { get; set; }

        [XmlElement("View")]
        public List<View> Items { get; set; }

        [XmlIgnore]
        public bool ItemsSpecified
        {
            get { return Items != null && Items.Count > 0; }
        }

        [XmlIgnore]
        public SPList UpdatedSPObject { get; internal set; }

        /// <summary>
        /// Updates, replaces or deletes views for a list
        /// </summary>
        /// <param name="list">The parent list where to update, replace or delete the views</param>
        /// <param name="parentWeb"></param>
        public void ImportDefinition(SPList list, SPWeb parentWeb)
        {
            foreach (View viewDefinition in Items)
            {
                viewDefinition.DisplayName = DeploymentHelper.Resolve(viewDefinition.DisplayName, parentWeb.Locale);
                SPView view = null;
                try
                {
                    view = list.Views[viewDefinition.DisplayName];
                }
                catch(Exception)
                {
                    // Catch if view does not exists
                }

                viewDefinition.ImportDefinition(view, list);
            }

            UpdatedSPObject = list;
        }
    }
}